package org.opens.netty.udp.server;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.opens.netty.udp.codec.LogEventEncoder;
import org.opens.netty.udp.entity.LogEvent;

import java.io.File;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;

public class LogEventServer extends Thread {

    private final EventLoopGroup group;

    private final Bootstrap bootstrap;

    private final File file;

    public LogEventServer(InetSocketAddress address, File file) {
        this.group = new NioEventLoopGroup();
        this.bootstrap = new Bootstrap();
        this.file = file;
        this.bootstrap.group(this.group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new LogEventEncoder(address));
    }

    @Override
    public void run() {
        try {
            Channel channel = this.bootstrap.bind(0).sync().channel();
            long pointer = 0;
            for (;;) {
                long len = file.length();
                if (len < pointer) {
                    pointer = len;
                } else if (len > pointer) {
                    try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
                        raf.seek(pointer);
                        String line;
                        while ((line = raf.readLine()) != null) {
                            System.out.println("读取到的新内容: " + line);
                            channel.writeAndFlush(new LogEvent(null, -1, file.getAbsolutePath(), line));
                        }
                        pointer = raf.getFilePointer();
                    }

                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.interrupted();
                    break;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void stopServer() {
        group.shutdownGracefully();
    }
}
